package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 *
 * @author zhangyu
 * @date 2025-05-30
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        //1.校验必填字段
        if (device.getId() == null) {
            throw new ServiceException("设备ID不能为空");
        }
        //2.校验设备存在性
        Device dbdevice = getById(device.getId());
        if (dbdevice == null) {
            throw new ServiceException("设备不存在");
        }
        //3.校验设备名称
        if (StringUtils.isNotEmpty(device.getDeviceName())
                && !device.getDeviceName().equals(dbdevice.getDeviceName())) {
            Long count = lambdaQuery()
                    .eq(Device::getDeviceName, device.getDeviceName())
                    .ne(Device::getId, device.getId())
                    .count();
            if (count > 0) {
                throw new ServiceException("设备名称已存在");
            }
            try {
                UpdateDeviceRequest request = new UpdateDeviceRequest();
                request.setDeviceId(dbdevice.getIotId());
                //...设置其他更新参数...
                client.updateDevice(request);
            } catch (Exception e) {
                log.error("华为云设备更新失败", e);
                throw new ServiceException("云端设备更新失败");
            }
            // 4.更新数据库
        }
        return updateById(device) ? 1 : 0;
    }


    /**
     * 删除设备信息
     *
     * @param iotId 设备主键
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDeviceByIotId(String iotId) {
        if (iotId == null) {
            throw new ServiceException("设备ID不能为空");
        }
        try {
            // 1. 先删除云端设备
            DeleteDeviceRequest request = new DeleteDeviceRequest()
                    .withDeviceId(iotId);
            DeleteDeviceResponse response = client.deleteDevice(request);

            // 检查华为云API响应状态（根据最新API文档调整）
            if (response.getHttpStatusCode() != 204) {
                log.error("云端删除失败，响应码：{}，响应体：{}",
                        response.getHttpStatusCode(),
                        response.getBody());
                throw new ServiceException("云端设备删除失败");
            }
        } catch (ServiceResponseException e) {
            // 处理设备不存在的情况（错误码参考华为云文档）
            if ("IoTDA.0041".equals(e.getErrorCode())) {
                log.warn("设备[{}]在云端已不存在", iotId);
            } else {
                log.error("华为云接口异常[{}]{}，请求ID：{}",
                        e.getErrorCode(),
                        e.getErrorMsg(),
                        e.getRequestId());
                throw new ServiceException("云端服务异常：" + e.getErrorMsg());
            }
        } catch (Exception e) {
            log.error("华为云通信异常", e);
            throw new ServiceException("云端通信失败");
        }
        return deviceMapper.deleteDeviceByIotId(iotId);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //设备名称不能重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new ServiceException("设备名称不能重复");
        }
        //设备标识码不能重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new ServiceException("设备标识码不能重复");
        }
        //同一个位置不能绑定同一类产品设备
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new ServiceException("该位置或老人已经绑定过同一类的产品设备了");
        }
        //请求华为云注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        // 设置设备的属性
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());
        //授权信息，密钥
        AuthInfo authInfo = new AuthInfo();
        // 设备的密钥
        String secret = UUID.fastUUID().toString(true);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDeviceRequest.setBody(addDevice);
        try {
            AddDeviceResponse response = client.addDevice(addDeviceRequest);
            //5、保存设备信息到数据库
            Device device = BeanUtil.toBean(deviceDto, Device.class);
            device.setIotId(response.getDeviceId());//iotId
            device.setSecret(secret);

            save(device);
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new ServiceException("注册设备失败！请稍候重试");
        }
    }

    /**
     * 查询设备
     *
     * @param iotId
     */
    @Override
    public DeviceDetailVo getDeviceInfo(String iotId) {
        //1、通过iotId查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new ServiceException("设备不存在");
        }
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //2、查询华为云平台上的设备数据
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        try {
            ShowDeviceResponse response = client.showDevice(showDeviceRequest);
            vo.setDeviceStatus(response.getStatus());
            String activeTimeStr = response.getActiveTime();
            if (StringUtils.isNotEmpty(activeTimeStr)) {
                LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);

                //日期时区转换, 当前所在的时区
                activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        // 转时区,获取系统中的时区
                        .withZoneSameInstant(ZoneId.systemDefault())
                        .toLocalDateTime();
                vo.setActiveTime(activeTime);
            }
        } catch (Exception e) {
            log.error("查询云平台上的设备数据失败", e);
            throw new ServiceException("查询云平台上的设备数据失败");
        }
        //3、组装到vo，返回
        return vo;
    }

    /**
     * 查询设备上报数据
     *
     * @param  iotId
     *
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //创建请求对象
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        //设置设备ID
        request.setDeviceId(iotId);
        //发起请求
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        //遍历数据
        List<Map<String, Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);

    }

    /**
     * 查询产品详情
     *
     * @param productKey
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        }catch(Exception e){
            throw new BaseException("查询产品详情失败");
        }
        List<ServiceCapability>serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(serviceCapabilities);
        }
        return AjaxResult.success(serviceCapabilities);
    }

    public static void main(String[] args) {
        System.out.println("ZoneId.systemDefault() = " + ZoneId.systemDefault());
    }
}
